﻿using Share;
using System.Collections;
using System.IO;
using UnityEngine;
#if UNITY_EDITOR

using UnityEditor;
public class ScreenshotMenu
{
    [MenuItem("工具/截屏 _F12")]
    private static void CaptureScreenshot()
    {
        if (Application.isPlaying)
            ScreenshotHelper.Instance.DoCapture();
    }
}
#endif
public class ScreenshotHelper : SingletonMonoObject<ScreenshotHelper>
{
    public void DoCapture()
    {
        StartCoroutine(CaptureScreenCoroutine());
    }

    private IEnumerator CaptureScreenCoroutine()
    {
        string picturesPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
        string saveDir = Path.Combine(picturesPath, "图片");
        if (!Directory.Exists(saveDir))
        {
            Directory.CreateDirectory(saveDir);
        }

        string fileName = $"Pic_{System.DateTime.Now:yyyyMMdd_HHmmss}.png";
        string fullPath = Path.Combine(saveDir, fileName);

        yield return new WaitForEndOfFrame();

        Texture2D screenShot = ScreenCapture.CaptureScreenshotAsTexture();
        if (screenShot == null)
        {
            XKLog.LogError("Failed to capture screenshot - texture is null");
            yield break;
        }

        byte[] bytes = screenShot.EncodeToPNG();
        File.WriteAllBytes(fullPath, bytes);
        Object.Destroy(screenShot);
        XKLog.LogError($"截屏成功:{fullPath}");

        // 截屏成功后打开对应目录
        OpenFileExplorer(saveDir);
    }

    /// <summary>
    /// 打开文件资源管理器到指定目录
    /// </summary>
    /// <param name="directoryPath">目录路径</param>
    private void OpenFileExplorer(string directoryPath)
    {
        if (!Directory.Exists(directoryPath))
        {
            XKLog.LogError($"目录不存在: {directoryPath}");
            return;
        }

        try
        {
            // 使用系统进程打开文件资源管理器
            System.Diagnostics.Process.Start(directoryPath);
            XKLog.Log($"已打开目录: {directoryPath}");
        }
        catch (System.Exception ex)
        {
            XKLog.LogError($"打开目录失败: {ex.Message}");
        }
    }
}
